﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Joy.Erp.BasicArchives.Suppliers;
using Joy.Erp.Ufida.Core;
using Microsoft.Extensions.Logging;

namespace Joy.Erp.Ufida.Suppliers
{
    public class SupplierTypeSyncAppService : UfidaAppService, ISupplierTypeSyncAppService
    {
        protected ISupplierTypeRepository SupplierTypeRepository => LazyServiceProvider.LazyGetRequiredService<ISupplierTypeRepository>();
        protected ISupplierTypeAppService SupplierTypeAppService => LazyServiceProvider.LazyGetRequiredService<ISupplierTypeAppService>();
        protected ISupplierCategoryUfidaAppService SupplierCategoryUfidaAppService => LazyServiceProvider.LazyGetRequiredService<ISupplierCategoryUfidaAppService>();
        protected SupplierTypeManager SupplierTypeManager => LazyServiceProvider.LazyGetRequiredService<SupplierTypeManager>();

        public async Task<AnalysisDto> Analyze‌Async()
        {
            var analysisDto = new AnalysisDto();
            analysisDto.Id = typeof(SupplierType).FullName;

            // 获取U9数据的ID列表
            var u9list = await SupplierCategoryUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID.ToString()).ToHashSet();
            analysisDto.U9Count = u9Ids.Count;

            // 使用数据库查询优化，只查询需要的字段
            var pmcQuery = await SupplierTypeRepository.GetQueryableAsync();

            // 获取PMC总数
            analysisDto.Count = await AsyncExecuter.CountAsync(pmcQuery.Where(x => !x.IsDeleted));

            // 获取已同步的SourceKey列表
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 快速计算已同步数量
            analysisDto.AsyncCount = syncedSourceKeys.Count(key => u9Ids.Contains(key));
            analysisDto.UnasyncCount = analysisDto.U9Count - analysisDto.AsyncCount;
            analysisDto.SelfCount = analysisDto.Count - analysisDto.AsyncCount;

            return analysisDto;
        }

        public async Task<List<long>> GetUnasyncIds()
        {
            // 获取U9的所有ID
            var u9list = await SupplierCategoryUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID).ToList();

            // 使用数据库查询，只查询已同步的SourceKey
            var pmcQuery = await SupplierTypeRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 优化查找性能，时间复杂度从 O(n²) 降到 O(n)
            var syncedSourceKeySet = new HashSet<string>(syncedSourceKeys);

            // 找出未同步的ID
            var unasyncIds = u9Ids
                .Where(id => !syncedSourceKeySet.Contains(id.ToString()))
                .ToList();

            return unasyncIds;
        }

        public async Task<int> CreateByIds‌Async(long[] ids)
        {
            if (ids == null || ids.Length == 0)
                return 0;

            // 批量预查询已存在的记录，避免循环查询数据库
            var pmcQuery = await SupplierTypeRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x =>
                        !x.IsDeleted
                        && x.SourceType == SourceConfig.SourceType
                        && idStrings.Contains(x.SourceKey)
                    )
                    .Select(x => x.SourceKey)
            );
            var existingSet = new HashSet<string>(existingSourceKeys);

            // 过滤出需要创建的ID
            var needCreateIds = ids.Where(id => !existingSet.Contains(id.ToString())).ToList();
            if (needCreateIds.Count == 0)
                return ids.Length;

            Logger.LogInformation($"[批量同步-供应商类型] 开始处理 {needCreateIds.Count} 条新增，已存在 {existingSet.Count} 条");

            // 为了确保父级先于子级创建，需要先获取U9数据并按Code长度排序
            var u9DataList = new List<(long id, SupplierCategoryUfidaDto dto)>();
            foreach (var id in needCreateIds)
            {
                try
                {
                    var supplierCategoryUfidaDto = await SupplierCategoryUfidaAppService.GetAsync(id);
                    if (supplierCategoryUfidaDto != null)
                    {
                        u9DataList.Add((id, supplierCategoryUfidaDto));
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商类型] 获取U9数据失败，Id: {id}");
                }
            }

            if (u9DataList.Count == 0) return existingSet.Count;

            // 按Code长度排序，确保父级先于子级创建
            var sortedList = u9DataList.OrderBy(x => x.dto.Code?.Length ?? int.MaxValue).ToList();

            var successCount = 0;
            using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
            {
                try
                {
                    foreach (var (id, dto) in sortedList)
                    {
                        try
                        {
                            var result = await CreateByIdAsync(id);
                            if (result)
                            {
                                successCount++;
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogWarning(ex, $"[批量同步-供应商类型] 创建实体失败，Id: {id}");
                        }
                    }

                    await uow.CompleteAsync();
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商类型] 批量创建失败，{ex.Message}");
                }
            }

            Logger.LogInformation($"[批量同步-供应商类型] 完成！成功新增 {successCount} 条，总计 {successCount + existingSet.Count} 条");

            return successCount + existingSet.Count;
        }

        public async Task<List<long>> GetSyncedIds()
        {
            var pmcQuery = await SupplierTypeRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            return syncedSourceKeys
                .Select(key => long.TryParse(key, out var parsedId) ? (long?)parsedId : null)
                .Where(id => id.HasValue)
                .Select(id => id.Value)
                .ToList();
        }

        public async Task<int> UpdateByIds‌Async(long[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;

            Logger.LogInformation($"[批量同步-供应商类型] 开始处理 {ids.Length} 条供应商类型更新/删除");

            var pmcQuery = await SupplierTypeRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingEntities = await AsyncExecuter.ToListAsync(
                pmcQuery.Where(x =>
                    !x.IsDeleted
                    && x.SourceType == SourceConfig.SourceType
                    && idStrings.Contains(x.SourceKey)
                )
            );

            if (existingEntities.Count == 0)
            {
                Logger.LogWarning($"[批量同步-供应商类型] 没有找到需要更新或删除的记录");
                return 0;
            }

            var entityDict = existingEntities.ToDictionary(x => x.SourceKey, x => x);

            var allU9DataDict = new Dictionary<long, SupplierCategoryUfidaDto>();
            foreach (var id in ids)
            {
                var key = id.ToString();
                if (!entityDict.ContainsKey(key)) continue;

                try
                {
                    var dto = await SupplierCategoryUfidaAppService.GetAsync(id);
                    if (dto != null)
                    {
                        allU9DataDict[id] = dto;
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商类型] 获取U9数据失败，Id: {id}");
                }
            }

            var entitiesToUpdate = new List<SupplierType>();
            var entitiesToDelete = new List<SupplierType>();
            foreach (var id in ids)
            {
                if (!entityDict.TryGetValue(id.ToString(), out var entity)) continue;

                try
                {
                    if (!allU9DataDict.TryGetValue(id, out var u9Data))
                    {
                        entitiesToDelete.Add(entity);
                        continue;
                    }

                    entity.DisplayName = u9Data.Name;
                    entity.SourceCreatedOn = u9Data.CreatedOn;

                    entitiesToUpdate.Add(entity);
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商类型] 处理实体失败，Id: {id}");
                }
            }

            if (entitiesToUpdate.Count == 0 && entitiesToDelete.Count == 0)
            {
                Logger.LogInformation($"[批量同步-供应商类型] 无需更新或删除记录");
                return 0;
            }

            var updateCount = 0;
            var deleteCount = 0;
            using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
            {
                try
                {
                    if (entitiesToUpdate.Count > 0)
                    {
                        await SupplierTypeRepository.BulkUpdateAsync(
                            entitiesToUpdate,
                            autoSave: false
                        );
                        updateCount = entitiesToUpdate.Count;
                    }

                    if (entitiesToDelete.Count > 0)
                    {
                        await SupplierTypeRepository.BulkDeleteAsync(
                            entitiesToDelete,
                            autoSave: false
                        );
                        deleteCount = entitiesToDelete.Count;
                    }

                    await uow.CompleteAsync();
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商类型] 批量更新/删除失败，{ex.Message}");
                }
            }

            Logger.LogInformation($"[批量同步-供应商类型] 完成！成功更新 {updateCount} 条，删除 {deleteCount} 条");

            return updateCount + deleteCount;
        }

        private async Task<bool> CreateByIdAsync(long id)
        {
            var existSupplierType = await SupplierTypeAppService.FindBySourceKeyAsync(id.ToString(), SourceConfig.SourceType);
            if (existSupplierType != null) return true;

            var supplierCategoryUfidaDto = await SupplierCategoryUfidaAppService.GetAsync(id);
            if (supplierCategoryUfidaDto == null) return false;

            try
            {
                await CreateAsync(supplierCategoryUfidaDto);
                return true;
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, $"CreateByIdAsync 创建失败，Id: {id}, 错误信息：{ex.Message}");
                return false;
            }
        }

        private async Task<SupplierTypeDto> CreateAsync(SupplierCategoryUfidaDto supplierCategoryUfidaDto)
        {
            var supplierTypeCreateDto = new SupplierTypeCreateDto();
            supplierTypeCreateDto.SourceType = SourceConfig.SourceType;
            supplierTypeCreateDto.SourceKey = supplierCategoryUfidaDto.ID.ToString();
            supplierTypeCreateDto.DisplayName = supplierCategoryUfidaDto.Name;
            supplierTypeCreateDto.SourceCreatedOn = supplierCategoryUfidaDto.CreatedOn;
            supplierTypeCreateDto.ParentId = null;
            //Code = supplierCategoryUfidaDto.Code,   树结构的Code在pmc中不能赋值，由CreateAsync自动生成

            // SupplierType 的父级关系处理：如果 Code 有层级结构，可以通过 Code 长度判断
            // 这里简化处理，如果需要处理父级关系，可以参考 ItemCategory 的实现
            // 由于 SupplierCategoryUfidaDto 没有 TreeRule，暂时不处理父级关系

            return await SupplierTypeAppService.CreateAsync(supplierTypeCreateDto);
        }
    }
}
